package cn.iocoder.yudao.module.trade.aftersale.service;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.enums.UserTypeEnum;
import cn.iocoder.yudao.framework.common.util.json.JsonUtils;
import cn.iocoder.yudao.framework.thirdparty.zxhx.ZXHXApiClientFactory;
import cn.iocoder.yudao.framework.thirdparty.zxhx.dto.ZXHXAfterSaleDetailRespDTO;
import cn.iocoder.yudao.framework.thirdparty.zxhx.dto.ZXHXMessageAfterSaleStatusRespDTO;
import cn.iocoder.yudao.framework.thirdparty.zxhx.dto.ZXHXMessagePoolRespDTO;
import cn.iocoder.yudao.framework.thirdparty.zxhx.dto.ZXHXMessageRemoveReqDTO;
import cn.iocoder.yudao.framework.thirdparty.zxhx.enums.ZXHXAfterSaleStatus;
import cn.iocoder.yudao.framework.thirdparty.zxhx.enums.ZXHXMessageType;
import cn.iocoder.yudao.module.api.trade.aftersale.enums.AfterSaleOperateTypeEnum;
import cn.iocoder.yudao.module.api.trade.aftersale.enums.AfterSaleStatusEnum;
import cn.iocoder.yudao.module.trade.aftersale.bo.AfterSaleLogCreateReqBO;
import cn.iocoder.yudao.module.trade.aftersale.dal.dataobject.AfterSaleDO;
import cn.iocoder.yudao.module.trade.aftersale.dal.mysql.AfterSaleMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;

/**
 * <pre>
 * OOoO0OOoO0OOOooo0oOOOO0OOOOO0oooOO0ooOOO0Ooooo0OOOOo0ooooO0OOooo0Ooooo0OOOOO
 *  这里是文件说明
 * OOoO0OOoO0OOOooo0oOOOO0OOOOO0oooOO0ooOOO0Ooooo0OOOOo0ooooO0OOooo0Ooooo0OOOOO
 * </pre>
 *
 * @author 山野羡民（1032694760@qq.com）
 * @since 2025/03/17
 */
@Service
@Validated
@Slf4j
public class ZXHXAfterSaleSyncServiceImpl implements ZXHXAfterSaleSyncService {
    @Resource
    private AfterSaleMapper afterSaleMapper;

    @Resource
    private AfterSaleLogService afterSaleLogService;

    @Override
    public int autoSync() {
        List<ZXHXMessagePoolRespDTO> messagePoolRespDTOS = ZXHXApiClientFactory.messageClient().getMessagePool(ZXHXMessageType.AFTER_SALES_STATUS_CHANGE, 1000);
        if (CollUtil.isEmpty(messagePoolRespDTOS)) {
            log.info("供应链({})没有新的消息", ZXHXMessageType.AFTER_SALES_STATUS_CHANGE.getName());
            return 0;
        }
        List<Integer> ids = new ArrayList<>();
        for (ZXHXMessagePoolRespDTO messagePoolRespDTO : messagePoolRespDTOS) {
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                log.warn("供应链同步售后信息线程休眠一定的毫秒数出错：{}", e.getMessage());
            }
            ZXHXMessageAfterSaleStatusRespDTO messageAfterSaleStatusRespDTO = JsonUtils.parseObject(messagePoolRespDTO.getContent(), ZXHXMessageAfterSaleStatusRespDTO.class);
            if (messageAfterSaleStatusRespDTO == null) {
                log.warn("供应链({})新的消息中没有解析出有效的 service_sn: {}", ZXHXMessageType.AFTER_SALES_STATUS_CHANGE.getName(), messagePoolRespDTO.getContent());
                continue;
            }
            AfterSaleDO afterSaleDO = afterSaleMapper.searchBySupplyRelatedNo(messageAfterSaleStatusRespDTO.getServiceSn());
            if (afterSaleDO == null) {
                log.warn("供应链({})新的消息中的 service_sn: {} 没有找到相关的售后订单", ZXHXMessageType.AFTER_SALES_STATUS_CHANGE.getName(), messageAfterSaleStatusRespDTO.getServiceSn());
                continue;
            }
            ids.add(messagePoolRespDTO.getId());
            syncAfterSaleInfoAsync(messageAfterSaleStatusRespDTO.getServiceSn(), afterSaleDO);
        }
        ZXHXApiClientFactory.messageClient().removeMessage(new ZXHXMessageRemoveReqDTO(ids));
        return ids.size();
    }

    @Async
    @Override
    public void syncAfterSaleInfoAsync(String serviceSn, AfterSaleDO afterSaleDO) {
        ZXHXAfterSaleDetailRespDTO afterSaleDetailRespDTO = ZXHXApiClientFactory.tradeClient().getAfterSaleDetail(serviceSn);
        boolean isUpdate = false;
        AfterSaleLogCreateReqBO afterSaleLogCreateReqBO = null;
        int beforeAfterSaleStatus = afterSaleDO.getStatus();
        if (afterSaleDetailRespDTO.getStatus() == ZXHXAfterSaleStatus.COMPLETED.getValue()) {
            afterSaleDO.setStatus(AfterSaleStatusEnum.COMPLETE.getStatus());
            afterSaleLogCreateReqBO = new AfterSaleLogCreateReqBO();
            afterSaleLogCreateReqBO.setUserId(0L);
            afterSaleLogCreateReqBO.setUserType(UserTypeEnum.ADMIN.getValue());
            afterSaleLogCreateReqBO.setAfterSaleId(afterSaleDO.getId());
            afterSaleLogCreateReqBO.setBeforeStatus(beforeAfterSaleStatus);
            afterSaleLogCreateReqBO.setAfterStatus(afterSaleDO.getStatus());
            afterSaleLogCreateReqBO.setOperateType(AfterSaleOperateTypeEnum.PLATFORM_REFUND.getType());
            afterSaleLogCreateReqBO.setContent(afterSaleDetailRespDTO.getEvents().stream()
                    .max(Comparator.comparing(ZXHXAfterSaleDetailRespDTO.EventsDTO::getId))
                    .map(ZXHXAfterSaleDetailRespDTO.EventsDTO::getRemark)
                    .orElse(AfterSaleOperateTypeEnum.PLATFORM_REFUND.getContent()));
            isUpdate = !Objects.equals(afterSaleDO.getStatus(), AfterSaleStatusEnum.COMPLETE.getStatus());
        }
        if (!isUpdate) {
            return;
        }
        log.info("供应链({})新的消息中的 order_sn: {}，异步地同步售后订单售后状态({}))", ZXHXMessageType.AFTER_SALES_STATUS_CHANGE.getName(), serviceSn, afterSaleDO.getStatus());
        afterSaleMapper.updateById(afterSaleDO);
        try {
            afterSaleLogService.createAfterSaleLog(afterSaleLogCreateReqBO);
        } catch (Throwable ex) {
            log.error("[syncOrderInfoAsync][订单({})创建售后日志({})出错]", afterSaleDO.getId(), afterSaleDO.getStatus(), ex);
        }
    }

}
